//
//  VideoControlView.swift
//  Mediaplayer
//
//  Created by bin hu on 2025/7/8.
//

import UIKit

class VideoControlView: UIView {
    
    // MARK: - 属性
    weak var delegate: VideoControlViewDelegate?
    
    private let playPauseButton = UIButton(type: .system)
    private let rateButton = UIButton(type: .system)
    private let progressSlider = UISlider()
    private let timeLabel = UILabel()
    
    private var rates: [Float] = [0.5, 1.0, 1.5, 2.0]
    private var currentRateIndex = 1
    private var totalDuration: Double = 0
    
    // MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - UI设置
    private func setupUI() {
        backgroundColor = UIColor.black.withAlphaComponent(0.6)
        layer.cornerRadius = 8
        
        // 播放/暂停按钮
        playPauseButton.setImage(UIImage(systemName: "pause.fill"), for: .normal)
        playPauseButton.theme_tintColor = "Colors.white"
        playPauseButton.addTarget(self, action: #selector(togglePlayPause), for: .touchUpInside)
        playPauseButton.translatesAutoresizingMaskIntoConstraints = false
        addSubview(playPauseButton)
        
        // 倍速按钮
        rateButton.setTitle("1.0x", for: .normal)
        rateButton.theme_setTitleColor("Colors.textColor.white", forState: .normal)
        rateButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        rateButton.addTarget(self, action: #selector(changePlaybackRate), for: .touchUpInside)
        rateButton.translatesAutoresizingMaskIntoConstraints = false
        addSubview(rateButton)
        
        // 进度条
        progressSlider.theme_minimumTrackTintColor = "Colors.main"
        progressSlider.theme_maximumTrackTintColor = "Colors.white"
        progressSlider.setThumbImage(UIImage(systemName: "circle.fill"), for: .normal)
        progressSlider.addTarget(self, action: #selector(sliderValueChanged(_:)), for: .valueChanged)
        progressSlider.addTarget(self, action: #selector(sliderTouchEnded(_:)), for: .touchUpInside)
        progressSlider.addTarget(self, action: #selector(sliderTouchEnded(_:)), for: .touchUpOutside)
        progressSlider.translatesAutoresizingMaskIntoConstraints = false
        addSubview(progressSlider)
        
        // 时间标签
        timeLabel.text = "0:00 / 0:00"
        timeLabel.theme_textColor = "Colors.textColor.white"
        timeLabel.font = UIFont.monospacedDigitSystemFont(ofSize: 12, weight: .regular)
        timeLabel.translatesAutoresizingMaskIntoConstraints = false
        addSubview(timeLabel)
        
        // 布局约束
        NSLayoutConstraint.activate([
            playPauseButton.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8),
            playPauseButton.centerYAnchor.constraint(equalTo: centerYAnchor),
            playPauseButton.widthAnchor.constraint(equalToConstant: 30),
            playPauseButton.heightAnchor.constraint(equalToConstant: 30),
            
            rateButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8),
            rateButton.centerYAnchor.constraint(equalTo: centerYAnchor),
            rateButton.widthAnchor.constraint(equalToConstant: 50),
            
            progressSlider.leadingAnchor.constraint(equalTo: playPauseButton.trailingAnchor, constant: 8),
            progressSlider.trailingAnchor.constraint(equalTo: rateButton.leadingAnchor, constant: -8),
            progressSlider.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -8),
            
            timeLabel.leadingAnchor.constraint(equalTo: playPauseButton.trailingAnchor, constant: 8),
            timeLabel.trailingAnchor.constraint(equalTo: rateButton.leadingAnchor, constant: -8),
            timeLabel.topAnchor.constraint(equalTo: progressSlider.bottomAnchor, constant: 2),
            timeLabel.heightAnchor.constraint(equalToConstant: 15)
        ])
    }
    
    // MARK: - 播放状态更新
    func setPlaybackState(_ isPlaying: Bool) {
        let imageName = isPlaying ? "pause.fill" : "play.fill"
        playPauseButton.setImage(UIImage(systemName: imageName), for: .normal)
    }
    
    // MARK: - 进度更新
    func setProgress(_ progress: Float, currentTime: Double) {
        guard !progressSlider.isTracking else { return }
        
        progressSlider.value = progress
        updateTimeLabel(currentTime: currentTime)
    }
    
    func setDuration(_ duration: Double) {
        totalDuration = duration
        let totalTime = formatTime(seconds: duration)
        timeLabel.text = "\(formatTime(seconds: 0)) / \(totalTime)"
    }
    
    private func updateTimeLabel(currentTime: Double) {
        let currentTimeStr = formatTime(seconds: currentTime)
        let totalTimeStr = formatTime(seconds: totalDuration)
        timeLabel.text = "\(currentTimeStr) / \(totalTimeStr)"
//        guard let text = timeLabel.text else { return }
//        let components = text.components(separatedBy: " / ")
//        if components.count == 2 {
//            let currentTimeStr = formatTime(seconds: currentTime)
//            timeLabel.text = "\(currentTimeStr) / \(components[1])"
//        }
    }
    
    private func formatTime(seconds: Double) -> String {
        guard seconds.isFinite else { return "0:00" }
        
        let totalSeconds = Int(seconds)
        let minutes = totalSeconds / 60
        let seconds = totalSeconds % 60
        return String(format: "%d:%02d", minutes, seconds)
    }
    
    // MARK: - 按钮事件
    @objc private func togglePlayPause() {
        delegate?.didTogglePlayPause()
    }
    
    // MARK: - 倍速
    @objc private func changePlaybackRate() {
        currentRateIndex = (currentRateIndex + 1) % rates.count
        let rate = rates[currentRateIndex]
        rateButton.setTitle("\(rate)x", for: .normal)
        delegate?.didChangePlaybackRate(rate)
    }
    
    // MARK: - 进度条事件
    @objc private func sliderValueChanged(_ sender: UISlider) {
        let currentTime = Double(sender.value) * totalDuration
        updateTimeLabel(currentTime: currentTime)
//        updateTimeLabel(currentTime: Double(sender.value) * (playerDuration ?? 1.0))
    }
    
    @objc private func sliderTouchEnded(_ sender: UISlider) {
        delegate?.didSeekTo(sender.value)
    }
    
//    private var playerDuration: Double? {
//        guard let text = timeLabel.text else { return nil }
//        let components = text.components(separatedBy: " / ")
//        if components.count == 2, let durationStr = components.last {
//            let parts = durationStr.components(separatedBy: ":")
//            if parts.count == 2,
//                let minutes = Int(parts[0]),
//                let seconds = Int(parts[1]) {
//                return Double(minutes * 60 + seconds)
//            }
//        }
//        return nil
//    }
}
